<?php
Cinnamon::loadClass('URLConnection');

/**
 * URL Reader class extending the URLConnection
 */
class URLReader extends URLConnection {
	/**
	 * The url
	 */
	protected $url;
	
	/**
	 * The cache contents of the url
	 */
	protected $contents;
	
	/**
	 * Default constructor
	 */
	public function __construct($url) {
		$this->url = $url;
	}
	
	/**
	 * Returns the title in UTF-8 encoding
	 */
	public function getTitle() {
		$this->readAndCacheContents();
		$title = null;
		
		if ( preg_match('!<title>([^<]*)<\/title>!ims', $this->contents, $matches) ) {
			$title = trim($matches[1]);
			
			Cinnamon::loadClass('Text');
			if ( Text::isUTF8($title) ) {
				return $title;
			}
			
			// try to guess the charset, if the document does not contain a charset statement
			$charset = nvl($this->getCharset(), 'ASCII, UTF-8, ISO-8859-1, JIS, EUC-JP, SJIS');
			
			if ( strcmp($charset, 'UTF-8') != 0 ) {		// if is UTF-8, do not convert!
				$title = Text::convertEncoding($title, 'UTF-8', $charset);
			}
		}
		
		return $title;
	}
	
	/**
	 * Returns the used charset, as defined in the (X)HTML document
	 */
	public function getCharset() {
		$this->readAndCacheContents();
		$charset = null;
		
		if ( preg_match('!charset=([^"]*)"!ims', $this->contents, $matches) ) {
			$charset = trim($matches[1]);
			$charset = strtoupper($charset); 
		}	
		
		return $charset;
	}
	
	/**
	 * Returns true only and only if it contains the cinnamon javascript code
	 */
	public function hasCinnamonCode($id) {
		$this->readAndCacheContents();

		$url = preg_quote(CSEURL .'/cse-javascript.php?site_id='. $id, '/');
		return ( preg_match('/'. $url .'/is', $this->contents) > 0 );
	}
}